package org.abstractmeta.commandify.core.command.accessor;

import org.abstractmeta.reflectify.Accessor;

import java.util.Collection;

/**
* Created with IntelliJ IDEA.
* User: adrianwit
* Date: 6/28/13
* Time: 9:43 PM
* To change this template use File | Settings | File Templates.
*/
public class CollectionAccessor<T> implements Accessor<Collection<T>, T> {

    private final Accessor<T, Object> uniqueKeyAccessor;
    private final Object matchingKey;

    public CollectionAccessor(Accessor<T, Object> uniqueKeyAccessor, Object matchingKey) {
        this.uniqueKeyAccessor = uniqueKeyAccessor;
        this.matchingKey = matchingKey;
    }

    @Override
    public T get(Collection<T> instance) {
        for (T t : instance) {
            Object keyCandidate = uniqueKeyAccessor.get(t);
            if (matchingKey.equals(keyCandidate)) {
                return t;
            }
        }
        return null;
    }

    public Accessor<T, Object> getUniqueKeyAccessor() {
        return uniqueKeyAccessor;
    }

    public Object getMatchingKey() {
        return matchingKey;
    }
}
